<!--
 * @Descripttion: 库存查询列表
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-02 15:03:05
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-12 15:12:19
 -->
<template>
  <div class="app-container">
    <Tab
      v-model="tabIndex"
      :texts="['即时库存']"
      @on-date-range="onDateRange"
      @on-click="onTabClick"
    >
      <span slot="reference">指定日期</span>
      <div class="fr" />
    </Tab>
    <div>
      <el-card shadow="never" class="oper-btn-card">
        <div class="clearfix">
          <el-form
            class="fl form-no-bottom"
            :inline="true"
            :model="searchData"
            label-position="left"
            label-width="80px"
            @keydown.enter.native="btnSearchData"
          >
            <el-form-item label="商品分类: ">
              <CatTreeSelect v-model="searchData.catId" />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="searchData.keywords"
                clearable
                style="width: 260px"
                placeholder="按商品编号，名称，规格查询"
              >
                <el-button slot="append" icon="el-icon-search" type="primary" :loading="btnLoading.search" @click="btnSearchData" />
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="searchData.isShowStopUse" style="margin-right:0;" true-label="1" false-label="0" border>不显示停用商品</el-checkbox>
              <el-checkbox v-model="searchData.isShowZeroStock" true-label="1" false-label="0" border>不显示0库存商品</el-checkbox>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <el-card shadow="never" class="oper-btn-card">
        <vxe-grid
          ref="table"
          class="grid"
          border
          resizable
          highlight-hover-row
          :loading="tableLoading.stock"
          :edit-config="{trigger: 'click', mode: 'row'}"
          :columns="columnsData"
          :data="tableData.stock"
        />
      </el-card>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="pageInfo.rows"
        :page-sizes="[20,30,40]"
        :current-page.sync="pageInfo.page"
        :total="pageInfo.total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>
    <el-dialog
      title="库存分布"
      width="800px"
      height="90%"
      :visible.sync="dialogVisible"
      destroy-on-close
      append-to-body
    >
      <GoodStock v-if="dialogVisible" :sku-id="currentRow.id" />
    </el-dialog>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import { getStockList } from '@/api/stock/stock.js'
import Affix from '@/components/Affix'
import Tab from '@/views/components/Tab'
import GoodStock from './good-stock'
import CatTreeSelect from '@/views/components/GoodsCatTreeSelect'
import { columns } from './mixins'

export default {
  name: 'StockList',
  filters: {
  },
  // eslint-disable-next-line vue/no-unused-components
  components: { Affix, Tab, CatTreeSelect, GoodStock },
  mixins: [oftenuse, columns],
  data() {
    return {
      searchData: {
        catId: '0',
        isShowStopUse: '1'
      },
      currentRow: {},
      stockInfo: {
        oper: 'add',
        data: {}
      },
      dialogVisible: false,
      optionsData: {},
      tabIndex: 0
    }
  },
  computed: {
    columnsData: function() {
      const tabIndex = this.tabIndex
      if (tabIndex === 0) return this.columnsImmediately
      return this.columnsDate
    }
  },
  watch: {
    'tabIndex': {
      handler(val) {
        this.getListData()
      }
    },
    'searchData.catId': {
      handler() {
        this.getListData()
      }
    },
    'searchData.isShowStopUse': {
      handler() {
        this.getListData()
      }
    },
    'searchData.isShowZeroStock': {
      handler() {
        this.getListData()
      }
    }
  },
  created() {
    this.getListData()
  },
  methods: {
    btnSearchData() {
      this.setBtnLoading('search', true)
      this.getListData().then(res => {
        this.setBtnLoading('search', false)
      }).catch(err => {
        console.log(err)
        this.setBtnLoading('search', false)
      })
    },
    btnMore(params) {
      const { row } = params
      const { id, name } = row
      this.$router.push({
        name: 'StockLogList',
        query: { id, name }
      })
    },
    btnGetStock(params) {
      this.currentRow = params.row
      this.dialogVisible = true
    },
    btnJump2Price(params) {
      const { row } = params
      const { id, code, name } = row
      this.$router.push({
        name: 'CostPriceLogList',
        query: { id, code, name }
      })
    },
    // table btns
    // api
    getListData(params = { data: this.searchData, page: this.pageInfo }) {
      this.setTableLoading('stock', true)
      return new Promise((resolve, reject) => {
        getStockList(params).then(res => {
          resolve(res)
          this.setTableLoading('stock', false)
          if (!res.data.flag) return this.$message.error({ title: '查询失败', message: res.data.message })
          const pageData = res.data.data
          const records = pageData.records
          records.forEach(item => {
            item.unitId = this.getBaseUnitId(item)
            item.unitMulti = 1
          })
          this.setTableData('stock', records)
          this.pageInfo.total = pageData.total
        }).catch(err => {
          this.setTableLoading('stock', false)
          this.$notify.error({ title: '查询异常！', message: err.message })
          reject(err)
        })
      })
    },
    /**
     * 获取当前存货
     */
    getQtyInStore(row) {
      const { originQuantity, quantityIn, quantityOut } = row
      const value = this.$amount(originQuantity)
        .add(quantityIn).subtract(quantityOut).format()
      return value
    },
    /**
     * 获取可用库存
     */
    getQtyCanuse(row) {
      const { originQuantity, waitQuantityIn, waitQuantityOut, quantityIn, quantityOut } = row
      const value = this.$amount(originQuantity).add(waitQuantityIn).add(quantityIn)
        .subtract(waitQuantityOut).subtract(quantityOut).format()
      return value
    },
    getBaseUnitId({ unitIdStr, unitNameStr, unitMultiStr, unitIsbaseStr }) {
      if (!unitIdStr) return null
      const unitIsbaseArr = unitIsbaseStr.split(',')
      const unitIdArr = unitIdStr.split(',')
      const index = unitIsbaseArr.findIndex(item => { return item === '1' })
      return unitIdArr[index]
    },
    // on
    onSizeChange(val) {
      this.pageInfo.current = 1
      this.pageInfo.size = val
      this.getListData()
    },
    onCurrentChange(val) {
      this.pageInfo.current = val
      this.getListData()
    },
    onDateRange(data) {
      debugger
    },
    onTabClick(data) {
    }
  }
}
</script>
<style scoped>

</style>
